package com.lijianlove.message.service.service.impl;

import com.lijianlove.message.common.enums.MsgStatusEnum;
import com.lijianlove.message.common.model.Message;
import com.lijianlove.message.common.model.RabbitMetaMessage;
import com.lijianlove.message.dal.MessageStoreService;
import com.lijianlove.message.dal.RabbitMetaMessageService;
import com.lijianlove.message.service.api.IMessageService;
import com.lijianlove.message.service.utils.RabbitMQSenderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author lijian
 * @date 2019/5/17 下午3:46
 */
@Slf4j
@Service
@RestController
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private RabbitMQSenderUtil rabbitMQSenderUtil;

    @Autowired
    private MessageStoreService messageStoreService;

    @Autowired
    private RabbitMetaMessageService rabbitMetaMessageService;

    @Override
    @PostMapping("/msg/pre")
    public String preMessage(@RequestBody Message msg) {
        log.info("preMessage,msg {}", msg);
        msg.setUniquMetaKey("9");
        msg.setCreateTime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MONTH, 2);
        msg.setExpireTime(calendar.getTime());

        if (ObjectUtils.isEmpty(msg.getUniquMetaKey())) {
            return null;
        }
        RabbitMetaMessage rabbitMetaMessage = this.rabbitMetaMessageService.get(msg.getUniquMetaKey());
        if (ObjectUtils.isEmpty(rabbitMetaMessage)) {
            return null;
        }


        /** 设置需要传递的消息体,可以是任意对象 */
        msg.setId(UUID.randomUUID().toString());
        msg.setBody(UUID.randomUUID().toString());
        /** 将消息设置为ready状态*/
        msg.setStatus(MsgStatusEnum.INIT);

        /** 持久化保存消息 */
        messageStoreService.save(msg);
        return msg.getId();
    }

    @Override
    @PostMapping("/msg/confirm")
    public void confirmAndSendMessage(@RequestParam String msgId) {
        log.info("confirmAndSendMessage,msgId {}", msgId);

        Message message = messageStoreService.get(msgId);

        RabbitMetaMessage rabbitMetaMessage = this.rabbitMetaMessageService.get(message.getUniquMetaKey());
        message.setStatus(MsgStatusEnum.WAIT);
        messageStoreService.updateStatus(message);
        rabbitMQSenderUtil.send(message, rabbitMetaMessage);
    }
}
